package com.highspeed.bdk.service.physical;

import com.highspeed.bdk.bean.entity.physical.Board;
import com.highspeed.bdk.bean.entity.physical.Cpu;
import com.highspeed.bdk.bean.entity.physical.MachineBox;
import com.highspeed.bdk.repository.physical.BoardRepository;
import com.highspeed.bdk.service.base.BdkBaseService;
import com.highspeed.bdk.utils.PhysicalDeviceUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by chenjiabin on 2018/3/23.
 */
@Service
@Transactional
public class BoardService extends BdkBaseService<Board, Integer> implements IBoardService {
    private static final Log LOG = LogFactory.getLog(BoardService.class);
    @Autowired
    private BoardRepository boardRepository;
    @Autowired
    private IMachineBoxService machineBoxService;

    @Override
    public BoardRepository getRepository() {
        return boardRepository;
    }

    @Override
    public Board save(Board entity) {
        initBoard(entity);
        return super.save(entity);
    }


    @Override
    public Board saveAndFlush(Board entity) {
        initBoard(entity);
        return super.saveAndFlush(entity);
    }

    @Override
    public <S extends Board> List<S> save(Iterable<S> entities) {
        if (entities != null) {
            for (Board board : entities) {
                initBoard(board);
            }
        }
        return super.save(entities);
    }

    private void initBoard(Board board) {
        PhysicalDeviceUtil.bindParent(board.getCpus(), board);
    }

    @Override
    public Board move(Integer boardId, Integer machineBoxId) {
        Board board = findOne(boardId);
        MachineBox machineBox = machineBoxService.findOne(machineBoxId);
        board.setMachineBox(machineBox);
        return save(board);
    }
}
